﻿/*******************************************************************
 *     JameE
 *******************************************************************
  Copyright 2010 Clifford Champion and JameE contributors.
  
  This file is part of JameE.
  
  JameE is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  JameE is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with JameE.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************/
 

//////
// JameE boostrapper.
//////



if(typeof($JameE) === "undefined")
{
	$JameE = null;
}

if (JameE_base_path == null) {
	JameE_base_path = "/";
}

(function(){

	var strBasePath = JameE_base_path;
	
	var iIncludeCounter = Number.MAX_VALUE;

	// check base path
	if (strBasePath[strBasePath.length - 1] !== "/") {
		throw new Error("Base path must end in a slash.");
	}

	// a simple script includer
	var fnIncludeScript = function (strPath) {
		var nodeScript = document.createElement("script");
		nodeScript.setAttribute("type", "text/javascript");
		nodeScript.setAttribute("src", strPath);
		nodeScript.setAttribute("async", true);
		var head = document.getElementsByTagName("head").item(0);
		head.appendChild(nodeScript);
	};

	// start including things
	fnIncludeScript(strBasePath + "Base/Classer.js");
	var bClasserLoaded = false;

	// onready queue
	var arr_fnOnReady = [];
	
	$JameE = function(fnOnReady)
	{
		if(fnOnReady === "Classer" && !bClasserLoaded)
		{
			bClasserLoaded = true;
			iIncludeCounter = 3;
			fnIncludeScript(strBasePath + "Base/IncludeLoader.js");
			fnIncludeScript(strBasePath + "Base/ObjectLoader.js");
			fnIncludeScript(strBasePath + "Base/Utils.js");
		}
		else if(typeof(fnOnReady) === "function"){
			if(iIncludeCounter>0) {
				arr_fnOnReady.push(fnOnReady);
			}
			else {
				fnOnReady();
			}
		}
		else if(fnOnReady === true)
		{
			// have we finished loading the core code?
			if(iIncludeCounter - 1 === 0)
			{
				// include the rest of the base and engine
				$include(
					[
						"Engine/Engine.js"
					],
					function() {
						
						--iIncludeCounter;

						var iNumFnOnReady = arr_fnOnReady.length;
						for(var iFn = 0; iFn < iNumFnOnReady; ++iFn)
						{
							arr_fnOnReady[iFn]();
						}
					}
				);
			}
			else {
				--iIncludeCounter;	
			}
		}
	};

})();

